package com.hardydou.framework.exception;

import cn.hutool.extra.servlet.ServletUtil;
import com.hardydou.common.result.Code;
import com.hardydou.common.result.NoConditionException;
import com.hardydou.common.result.Result;
import com.hardydou.common.result.ResultHelper;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author ：hardy
 * @description：
 * @date ：Created in 2020-03-17
 * @Copyright ：Hardydou.com
 */
@ControllerAdvice
public class AppExceptionHandler {


    @ExceptionHandler(NoConditionException.class)
    public Object NoConditionException(HttpServletRequest request, HttpServletResponse response, NoConditionException exception) throws Exception {
        Code code = exception.getCode();
        if (isAjax(request)) {
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            modelAndView.addObject("code", code.getCode());
            modelAndView.addObject("message", code.getTip());
            modelAndView.addObject("retry", code.isRetry());
            return modelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/error");
        request.setAttribute("message", exception.toString());
        return modelAndView;
    }


    @ExceptionHandler(LoginException.class)
    public Result loginException(HttpServletRequest request, LoginException exception) {
        return ResultHelper.error(exception);
    }


    private boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(header);
    }

}
